/**
 * 商品店铺关联脚本
 * 创建店铺并将现有商品关联到店铺
 */

const mongoose = require('mongoose');
const Shop = require('../src/models/shop.model');
const Product = require('../src/models/product.model');
const User = require('../src/models/user.model');
require('dotenv').config();

// 连接数据库
const connectDB = async () => {
  try {
    await mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/jd-mall');
    console.log('✅ 数据库连接成功');
  } catch (error) {
    console.error('❌ 数据库连接失败:', error);
    process.exit(1);
  }
};

// 创建测试店铺数据
const createTestShops = async () => {
  try {
    console.log('🏪 开始创建测试店铺...');

    // 获取或创建测试用户作为店主
    let testUsers = await User.find().limit(5);
    if (testUsers.length === 0) {
      console.log('👤 创建测试用户...');
      const testUserData = [
        { name: 'Apple官方', email: 'apple@shop.com', password: 'password123' },
        { name: '小米官方', email: 'xiaomi@shop.com', password: 'password123' },
        { name: '华为官方', email: 'huawei@shop.com', password: 'password123' },
        { name: '京东数码', email: 'jd@shop.com', password: 'password123' },
        { name: '潮流服饰', email: 'fashion@shop.com', password: 'password123' }
      ];
      
      testUsers = await User.insertMany(testUserData);
      console.log(`✅ 创建了 ${testUsers.length} 个测试用户`);
    }

    // 店铺数据
    const shopData = [
      {
        name: 'Apple官方旗舰店',
        description: 'Apple官方授权旗舰店，正品保证，全国联保',
        logo: 'https://picsum.photos/200/200?random=101',
        banner: 'https://picsum.photos/800/300?random=201',
        owner: testUsers[0]._id,
        type: 'official',
        status: 'active',
        categories: ['手机数码', '电脑办公'],
        rating: { overall: 4.9, service: 4.9, logistics: 4.8, description: 4.9 },
        announcement: '新品iPhone 15系列现货发售，享受官方保修服务',
        tags: ['官方正品', '全国联保', '快速发货'],
        certification: { isVerified: true, verifiedAt: new Date() },
        shipping: { freeShippingThreshold: 0, shippingFee: 0, supportedRegions: ['全国'], averageDeliveryTime: 1 },
        afterSales: { returnPolicy: '15天无理由退货', warrantyPeriod: 365, supportRefund: true, supportExchange: true },
        stats: { totalProducts: 0, totalSales: 10000, totalOrders: 5000, monthlyRevenue: 500000, followers: 50000 }
      },
      {
        name: '小米官方旗舰店',
        description: '小米科技官方旗舰店，米粉专属购物天堂',
        logo: 'https://picsum.photos/200/200?random=102',
        banner: 'https://picsum.photos/800/300?random=202',
        owner: testUsers[1]._id,
        type: 'official',
        status: 'active',
        categories: ['手机数码', '智能家居'],
        rating: { overall: 4.8, service: 4.8, logistics: 4.7, description: 4.8 },
        announcement: '小米14系列新品上市，性价比之王',
        tags: ['性价比', '科技潮品', '快速发货'],
        certification: { isVerified: true, verifiedAt: new Date() },
        shipping: { freeShippingThreshold: 99, shippingFee: 10, supportedRegions: ['全国'], averageDeliveryTime: 2 },
        afterSales: { returnPolicy: '7天无理由退货', warrantyPeriod: 365, supportRefund: true, supportExchange: true },
        stats: { totalProducts: 0, totalSales: 15000, totalOrders: 8000, monthlyRevenue: 300000, followers: 80000 }
      },
      {
        name: '华为官方旗舰店',
        description: '华为技术有限公司官方旗舰店',
        logo: 'https://picsum.photos/200/200?random=103',
        banner: 'https://picsum.photos/800/300?random=203',
        owner: testUsers[2]._id,
        type: 'official',
        status: 'active',
        categories: ['手机数码', '电脑办公'],
        rating: { overall: 4.7, service: 4.7, logistics: 4.6, description: 4.7 },
        announcement: 'Mate系列新品发布，科技美学新高度',
        tags: ['科技创新', '品质保证', '官方正品'],
        certification: { isVerified: true, verifiedAt: new Date() },
        shipping: { freeShippingThreshold: 199, shippingFee: 15, supportedRegions: ['全国'], averageDeliveryTime: 2 },
        afterSales: { returnPolicy: '7天无理由退货', warrantyPeriod: 365, supportRefund: true, supportExchange: true },
        stats: { totalProducts: 0, totalSales: 8000, totalOrders: 4000, monthlyRevenue: 400000, followers: 60000 }
      },
      {
        name: '京东数码专营店',
        description: '专业数码产品销售，品质保证，服务至上',
        logo: 'https://picsum.photos/200/200?random=104',
        banner: 'https://picsum.photos/800/300?random=204',
        owner: testUsers[3]._id,
        type: 'authorized',
        status: 'active',
        categories: ['手机数码', '摄影摄像'],
        rating: { overall: 4.6, service: 4.6, logistics: 4.5, description: 4.6 },
        announcement: '数码新品大促销，限时优惠不容错过',
        tags: ['品质保证', '价格优惠', '服务专业'],
        certification: { isVerified: true, verifiedAt: new Date() },
        shipping: { freeShippingThreshold: 299, shippingFee: 20, supportedRegions: ['全国'], averageDeliveryTime: 3 },
        afterSales: { returnPolicy: '7天无理由退货', warrantyPeriod: 180, supportRefund: true, supportExchange: true },
        stats: { totalProducts: 0, totalSales: 12000, totalOrders: 6000, monthlyRevenue: 200000, followers: 30000 }
      },
      {
        name: '潮流服饰旗舰店',
        description: '时尚潮流服饰，引领穿搭新风尚',
        logo: 'https://picsum.photos/200/200?random=105',
        banner: 'https://picsum.photos/800/300?random=205',
        owner: testUsers[4]._id,
        type: 'flagship',
        status: 'active',
        categories: ['服装鞋帽', '箱包配饰'],
        rating: { overall: 4.5, service: 4.5, logistics: 4.4, description: 4.5 },
        announcement: '春季新品上市，时尚潮流不容错过',
        tags: ['时尚潮流', '品质面料', '快速发货'],
        certification: { isVerified: false },
        shipping: { freeShippingThreshold: 199, shippingFee: 15, supportedRegions: ['全国'], averageDeliveryTime: 3 },
        afterSales: { returnPolicy: '7天无理由退货', warrantyPeriod: 90, supportRefund: true, supportExchange: true },
        stats: { totalProducts: 0, totalSales: 20000, totalOrders: 15000, monthlyRevenue: 150000, followers: 25000 }
      }
    ];

    // 清空现有店铺
    await Shop.deleteMany({});
    console.log('🗑️ 已清空现有店铺数据');

    // 创建店铺
    const shops = await Shop.insertMany(shopData);
    console.log(`✅ 成功创建 ${shops.length} 个店铺`);

    return shops;
  } catch (error) {
    console.error('❌ 创建店铺失败:', error);
    throw error;
  }
};

// 将商品关联到店铺
const linkProductsToShops = async (shops) => {
  try {
    console.log('🔗 开始关联商品到店铺...');

    // 获取所有商品
    const products = await Product.find();
    console.log(`📦 找到 ${products.length} 个商品`);

    if (products.length === 0) {
      console.log('⚠️ 没有找到商品，请先创建商品数据');
      return;
    }

    // 根据商品品牌或类别智能分配店铺
    let updatedCount = 0;
    
    for (const product of products) {
      let assignedShop = null;

      // 根据品牌分配店铺
      if (product.brand && product.brand.toLowerCase().includes('apple') || 
          product.name.toLowerCase().includes('iphone') || 
          product.name.toLowerCase().includes('ipad') ||
          product.name.toLowerCase().includes('mac')) {
        assignedShop = shops.find(shop => shop.name.includes('Apple'));
      } else if (product.brand && product.brand.toLowerCase().includes('xiaomi') || 
                 product.brand.toLowerCase().includes('小米') ||
                 product.name.toLowerCase().includes('小米')) {
        assignedShop = shops.find(shop => shop.name.includes('小米'));
      } else if (product.brand && product.brand.toLowerCase().includes('huawei') || 
                 product.brand.toLowerCase().includes('华为') ||
                 product.name.toLowerCase().includes('华为')) {
        assignedShop = shops.find(shop => shop.name.includes('华为'));
      } else if (product.category && product.category.includes('服装') || 
                 product.category.includes('鞋帽') ||
                 product.category.includes('配饰')) {
        assignedShop = shops.find(shop => shop.name.includes('潮流服饰'));
      } else {
        // 默认分配到京东数码专营店
        assignedShop = shops.find(shop => shop.name.includes('京东数码'));
      }

      // 如果没有匹配的店铺，随机分配一个
      if (!assignedShop) {
        assignedShop = shops[Math.floor(Math.random() * shops.length)];
      }

      // 更新商品的店铺关联
      await Product.findByIdAndUpdate(product._id, { shop: assignedShop._id });
      updatedCount++;

      console.log(`📱 ${product.name} → ${assignedShop.name}`);
    }

    console.log(`✅ 成功关联 ${updatedCount} 个商品到店铺`);

    // 更新店铺的商品统计
    for (const shop of shops) {
      const productCount = await Product.countDocuments({ shop: shop._id });
      await Shop.findByIdAndUpdate(shop._id, { 
        'stats.totalProducts': productCount 
      });
      console.log(`📊 ${shop.name}: ${productCount} 个商品`);
    }

  } catch (error) {
    console.error('❌ 关联商品到店铺失败:', error);
    throw error;
  }
};

// 主函数
const main = async () => {
  try {
    await connectDB();
    
    console.log('🚀 开始商品店铺关联流程...\n');
    
    // 1. 创建测试店铺
    const shops = await createTestShops();
    console.log('');
    
    // 2. 关联商品到店铺
    await linkProductsToShops(shops);
    console.log('');
    
    console.log('🎉 商品店铺关联完成！');
    console.log('📋 店铺列表:');
    shops.forEach((shop, index) => {
      console.log(`${index + 1}. ${shop.name} (${shop.type})`);
    });
    
  } catch (error) {
    console.error('❌ 流程执行失败:', error);
  } finally {
    await mongoose.connection.close();
    console.log('\n👋 数据库连接已关闭');
  }
};

// 运行脚本
if (require.main === module) {
  main();
}

module.exports = { main };
